<template>
  <div class="login-container">
    <el-card class="login-card">

      <template #header>
        <div class="card-header">
          <span>用户登录</span>
        </div>
      </template>

      <el-form
        ref="loginFormRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        size="large"
      >
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" class="custom-input"/>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            show-password
            placeholder="请输入密码"
          />
        </el-form-item>

        <!-- 记住登录状态 -->
        <el-form-item>
          <el-checkbox v-model="form.rememberMe">记住登录状态</el-checkbox>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            style="width: 100%"
            :loading="loading"
            @click="submitForm(loginFormRef)"
          >
            登录
          </el-button>
        </el-form-item>

        <!-- 注册链接 -->
        <div style="text-align: right">
          没有账号？
          <router-link to="/registration">去注册</router-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
defineOptions({ name: 'LoginPage' });
import { reactive, ref} from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import api from '../utils/request';
import { useAuthStore } from '@/stores/auth';

const router = useRouter();
const loginFormRef = ref();
const loading = ref(false);

// 表单数据
const form = reactive({
  username: '',
  password: '',
  rememberMe: false,
});

// 校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { pattern: /^\w{3,16}$/, message: '格式错误：3-16位字母/数字/下划线', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, max: 20, message: '长度8-20位', trigger: 'blur' },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,20}$/, message: '需包含字母和数字', trigger: 'blur' },
  ],
};

// 提交登录
const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (!valid) return;
    loading.value = true;

    // 调用登录接口
    api.post('/api/auth/login', {
      username: form.username,
      password: form.password,
      rememberMe: form.rememberMe
    })
    .then(async (response) => {
      const res = response.data;
      if (res.success) {
        const user = res.data;
        const authStore = useAuthStore();
        authStore.setToken(user.token);
        authStore.setUser(user);
        
        if (form.rememberMe) {
          localStorage.setItem('token', user.token);
          localStorage.setItem('user', JSON.stringify(user));
        }
        
        ElMessage.success(res.message || '登录成功！');
        
        // 登录成功后，获取完整的用户信息并存储
        try {
          const profileResponse = await api.get(`/api/user/profile/${user.userId}`);
          if (profileResponse.data.success) {
            const profileData = profileResponse.data.data;
            // 将完整的用户信息存储到认证状态中
            authStore.setUser({
              ...user,
              ...profileData
            });
            
            // 如果选择了记住登录，也更新localStorage中的用户信息
            if (form.rememberMe) {
              localStorage.setItem('user', JSON.stringify({
                ...user,
                ...profileData
              }));
            }
          }
        } catch (error) {
          console.warn('获取用户详细信息失败，使用基础登录信息:', error);
        }
        
        router.push('/UserInfoManagement');
      } else {
        ElMessage.error(res.message || '用户名或密码错误');
      }
    })
    .catch((error) => {
      ElMessage.error(error.response?.data?.message || '登录失败');
    })
    .finally(() => {
      loading.value = false;
    });
  });
};
</script>

<style scoped>
.login-container {
  height: 100vh;
  /* 添加背景图片 */
  background-image: url('@/assets/picture/background2.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  /* 保留原有渐变，可叠加 */
  background-blend-mode: lighten;

  display: flex;
  align-items: center;
  justify-content: center;
}
.login-card {
  width: 820px;
  padding: 0 20px 10px;
  height: 400px;
  background-color: rgba(255, 255, 255, 0.7); /* 半透明白色 */
  backdrop-filter: blur(1px); /* 毛玻璃效果，可选 */
  box-shadow: 0 4px 24px rgba(0,0,0,0.08);
}
.card-header {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
}

</style>
